package com.yanyeori.framework.security.config;

import com.yanyeori.framework.core.constant.BaseWebCodeEnum;
import com.yanyeori.framework.core.model.WebResponse;
import com.yanyeori.framework.core.util.ServletUtil;
import com.yanyeori.framework.security.constant.SecurityConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

/**
 * 认证失败处理类，返回401
 *
 * @author chenkuan 2020/11/20
 */
@Slf4j
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        int code = BaseWebCodeEnum.FORBIDDEN.code();
        String msg = ServletUtil.readAttributeFromRequest(request, SecurityConst.ERR_MSG_KEY);
        if (msg == null) {
            code = BaseWebCodeEnum.UNAUTHORIZED.code();
            msg = BaseWebCodeEnum.UNAUTHORIZED.msg();
        }
        log.info(msg);
        ServletUtil.writeToResponse(response, code, WebResponse.fail(code, msg));
    }
}
